package com.rc.fragment;

import java.util.ArrayList;
import java.util.HashMap;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.rc.activity.R;
import com.rc.activity.ReceiptBox;
import com.rc.activity.ReceiptBox.OnBackPressedListener;
import com.rc.activity.ReceiptBox.OnOpenSliding;
import com.rc.activity.ReportEdit;
import com.rc.activity.TripList;
import com.rc.activity.dao.tbl_Category;
import com.rc.activity.dao.tbl_CategoryDao;
import com.rc.activity.dao.tbl_Item;
import com.rc.activity.dao.tbl_ItemDao;
import com.rc.activity.dao.tbl_Report;
import com.rc.activity.dao.tbl_ReportDao;
import com.rc.activity.dao.tbl_Trip;
import com.rc.activity.dao.tbl_TripItems;
import com.rc.activity.dao.tbl_TripItemsDao;
import com.rc.activity.provider.Contract;
import com.rc.adapter.ReportDetailAdapter;
import com.rc.adapter.ReportDetailAdapter.OnItemChild;
import com.rc.db.DatabaseSupport;
import com.rc.util.Util;
import com.telpoo.frame.ui.BaseFragment;
import com.telpoo.frame.utils.Utils;

@SuppressLint("ValidFragment")
public class ReportDetailFragment extends BaseFragment implements
		OnClickListener, OnBackPressedListener, OnItemChild, OnOpenSliding {

	private RelativeLayout rlTotal;
	private LinearLayout llSubtotal, llTitle;
	private TextView txtTotal, txtReportTotal, txtReportName, txtApproverEmail,
			txtReference, txtReportTime, txtTripName, txtReportType;
	public static TextView txtMoney;
	private ImageView imgArrow;
	private boolean isShow = true;
	private ExpandableListView lvReportDetail;
	private tbl_Report objReport;
	private ArrayList<tbl_Trip> arrObjTrip;
	private int colorText;
	private String reportKey;
	private long reportID;
	private Cursor cursor;
	private LinearLayout llDelete, llActionSubmit, llApprove, llReject,
			llUpdate, llAction;
	private tbl_Trip objTrip;
	private Dialog dialog;
	private ReportDetailAdapter adpReportDetail;
	private int start, end;
	private boolean myReportDetailBroadcast = false;

	public ReportDetailFragment() {
		super();
	}

	public ReportDetailFragment(long reportID, String reportKey, int start,
			int end) {
		super();
		this.reportID = reportID;
		this.reportKey = reportKey;
		this.start = start;
		this.end = end;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View v;
		v = (ViewGroup) inflater.inflate(R.layout.report_detail, null);
		((ReceiptBox) getActivity())
				.setTitle(getString(R.string.report_detail));
		((ReceiptBox) getActivity()).setLogo(R.drawable.ic_top_travelexpense);
		((ReceiptBox) getActivity())
				.setOnBackPressedListener(new ReportDetailFragment(reportID,
						reportKey, start, end));
		((ReceiptBox) getActivity()).setOnOpenSliding(new ReportDetailFragment(
				reportID, reportKey, start, end));

		((ReceiptBox) getActivity()).setBackground(
				R.color.background_report_title, getResources());
		txtMoney = (TextView) v.findViewById(R.id.txtMoney);
		txtTotal = (TextView) v.findViewById(R.id.txtTotal);
		txtReportName = (TextView) v.findViewById(R.id.txtReportName);
		txtReportTime = (TextView) v.findViewById(R.id.txtReportTime);
		txtReportTotal = (TextView) v.findViewById(R.id.txtReportTotal);
		txtReference = (TextView) v.findViewById(R.id.txtReference);
		txtTripName = (TextView) v.findViewById(R.id.txtTripName);
		txtApproverEmail = (TextView) v.findViewById(R.id.txtApproverEmail);
		txtReportType = (TextView) v.findViewById(R.id.txtReportType);
		imgArrow = (ImageView) v.findViewById(R.id.imgArrow);
		llSubtotal = (LinearLayout) v.findViewById(R.id.llsubtotal);
		llTitle = (LinearLayout) v.findViewById(R.id.llTitle);
		rlTotal = (RelativeLayout) v.findViewById(R.id.rlTotal);
		lvReportDetail = (ExpandableListView) v.findViewById(R.id.lvTripItem);
		llApprove = (LinearLayout) v.findViewById(R.id.llApprove);
		llDelete = (LinearLayout) v.findViewById(R.id.llDelete);
		// llArchive = (LinearLayout) v.findViewById(R.id.llArchive);
		llAction = (LinearLayout) v.findViewById(R.id.llAction);
		llReject = (LinearLayout) v.findViewById(R.id.llReject);
		llActionSubmit = (LinearLayout) v.findViewById(R.id.llActionSubmit);
		llDelete = (LinearLayout) v.findViewById(R.id.llDelete);
		llUpdate = (LinearLayout) v.findViewById(R.id.llUpdate);

		llUpdate.setOnClickListener(this);
		llDelete.setOnClickListener(this);
		llActionSubmit.setOnClickListener(this);
		llReject.setOnClickListener(this);
		// llArchive.setOnClickListener(this);
		llApprove.setOnClickListener(this);
		rlTotal.setOnClickListener(this);
		llTitle.setOnClickListener(this);
		reportBroadcast = new ReportUpdateBroadcast();
		return v;
	}

	@Override
	public void onResume() {
		super.onResume();
		if (!myReportDetailBroadcast) {
			getActivity().registerReceiver(reportBroadcast,
					new IntentFilter("update.report.detail"));
			myReportDetailBroadcast = true;
		}
		objReport = new tbl_Report();
		objReport = DatabaseSupport.getReportByID(reportID, getActivity());
		// get color text
		if (objReport == null) {
			return;
		}
		String mReportType = objReport.getReportType();
		if (getActivity().getString(R.string.approved_reports).equals(
				mReportType)) {
			colorText = getActivity().getResources().getColor(
					R.color.background_color_approved);
		} else if (getActivity().getString(R.string.draft_reports).equals(
				mReportType)) {
			colorText = getActivity().getResources().getColor(
					R.color.background_color_draft);
		} else if (getActivity().getString(R.string.pending_reports).equals(
				mReportType)) {
			colorText = getActivity().getResources().getColor(
					R.color.background_color_pendding);
		} else if (getActivity().getString(R.string.rejected_reports).equals(
				mReportType)) {
			colorText = getActivity().getResources().getColor(
					R.color.background_color_reject);
		} else if (getActivity().getString(R.string.submitted_reports).equals(
				mReportType)) {
			colorText = getActivity().getResources().getColor(
					R.color.background_color_submitted);
		}
		actionShowBarBottom(mReportType);
		arrObjTrip = new ArrayList<tbl_Trip>();
		arrObjTrip = DatabaseSupport.getTripbyReportID(objReport.getReportID()
				+ "", getActivity());

		objTrip = new tbl_Trip();
		txtMoney.setText("$"
				+ Util.formatStringFloat(sumTotal(objReport.getReportType()
						.equals(getString(R.string.draft_reports)) ? true
						: false)));
		for (tbl_Trip objTrip : arrObjTrip) {
			this.objTrip = objTrip;
			txtTripName.setText(objTrip.getName());
			String categories = objTrip.getCategories();
			ArrayList<String> arrParens = new ArrayList<String>();
			String[] cateStrings = null;
			if (!"".equals(categories)) {
				categories = categories.replace("null,", "");
				if (categories.indexOf(",") >= 0) {
					cateStrings = categories.split(",");
					for (String string : cateStrings) {
						arrParens.add(string);
					}
				} else {
					if (!"false".equals(categories)) {
						arrParens.add(categories);
					}
				}
			}

			if (arrParens.size() > 0) {
				ArrayList<HashMap<String, ArrayList<tbl_Item>>> arrHmItems = new ArrayList<HashMap<String, ArrayList<tbl_Item>>>();
				HashMap<String, ArrayList<tbl_Item>> hmItems = new HashMap<String, ArrayList<tbl_Item>>();
				ArrayList<tbl_Category> arrCategoryAdd = new ArrayList<tbl_Category>();
				ArrayList<tbl_Item> arrItem = new ArrayList<tbl_Item>();
				for (String string : arrParens) {
					cursor = getActivity().getContentResolver().query(
							Contract.CONTENT_URI_ITEMS,
							null,
							tbl_ItemDao.Properties.CategoryID.columnName
									+ " = '" + string + "' and "
									+ tbl_ItemDao.Properties.TripID.columnName
									+ " = '" + objTrip.getTripID() + "'", null,
							null);

					arrItem = tbl_Item.getObjectbyCursor(cursor);
					cursor = getActivity().getContentResolver().query(
							Contract.CONTENT_URI_CATEGORY,
							null,
							tbl_CategoryDao.Properties.CategoryID.columnName
									+ " = '" + string + "'", null, null);
					ArrayList<tbl_Category> arrCategory = new ArrayList<tbl_Category>();
					arrCategory = tbl_Category.getObjectbyCursor(cursor);
					for (tbl_Category objCategory : arrCategory) {
						hmItems.put(objCategory.getName(), arrItem);
						arrCategoryAdd.add(objCategory);
					}

					arrHmItems.add(hmItems);
				}

				adpReportDetail = new ReportDetailAdapter(arrCategoryAdd,
						arrHmItems, this, mReportType);
				LayoutInflater inflater = LayoutInflater.from(getActivity());
				adpReportDetail.setInflater(inflater, getActivity());
				lvReportDetail.setGroupIndicator(null);
				lvReportDetail.setAdapter(adpReportDetail);
				lvReportDetail
						.setOnGroupClickListener(new OnGroupClickListener() {

							@Override
							public boolean onGroupClick(
									ExpandableListView parent, View v,
									int groupPosition, long id) {
								// thay doi image view khi explan
								v = adpReportDetail.getGroupView(groupPosition,
										true, v, parent);
								ImageView imgView_down = (ImageView) v
										.findViewById(R.id.imgView_down);
								ImageView imgView_up = (ImageView) v
										.findViewById(R.id.imgView_up);
								if (imgView_down.getVisibility() == View.GONE) {
									imgView_down.setVisibility(View.VISIBLE);
									imgView_up.setVisibility(View.GONE);
								} else {
									imgView_down.setVisibility(View.GONE);
									imgView_up.setVisibility(View.VISIBLE);
								}
								return false;
							}
						});
			}
		}

		Util.setListViewHeightBasedOnChildren(lvReportDetail);
		txtTotal.setTextColor(colorText);
		txtMoney.setTextColor(colorText);
		txtReportTime.setText(objReport.getCreatedTime());
		String reportType = objReport.getReportType();
		reportType = reportType.replace(getString(R.string.reports), "");
		txtReportType.setText(reportType);
		txtReportName.setTextColor(colorText);
		txtReportName.setText(objReport.getTitle());
		txtReportTotal.setText("$"
				+ Util.formatStringFloat(Util.convertFloat(objReport
						.getAmount())) + "");
		txtReference.setText(objReport.getReference());
		txtApproverEmail.setText(objReport.getApproverEmail());

	}

	@Override
	public void onPause() {
		super.onPause();
		if (myReportDetailBroadcast) {
			getActivity().unregisterReceiver(reportBroadcast);
			myReportDetailBroadcast = false;
		}

	}

	private void submitReport() {
		objReport.setIsUpdate("1");
		objReport.setReportType(getString(R.string.submitted_reports));
		objReport.setIsSubmitted(1);
		updateReport(objReport);
		// update trip item
		ArrayList<tbl_TripItems> arrTripItems = new ArrayList<tbl_TripItems>();
		arrTripItems = DatabaseSupport.getTripItemsByTripID(
				objTrip.getTripID(), getActivity());
		for (tbl_TripItems objTripItem : arrTripItems) {
			objTripItem.setApproved(objTripItem.getClaimed());
			objTripItem.setIsUpdate("1");
			getActivity().getContentResolver().update(
					Contract.CONTENT_URI_TRIP_ITEM,
					objTripItem.getContentValues(),
					tbl_TripItemsDao.Properties.TripItemID.columnName + " = "
							+ objTripItem.getTripItemID(), null);
		}
		showToast(getString(R.string.report_is_submitted));
		Util.pushFragmentReceiptBox(new ReportFragment(reportKey, start, end),
				getActivity(), "1");
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.rlTotal:
			if (isShow) {
				animation(isShow);
				isShow = false;
			} else {
				animation(isShow);
				isShow = true;
			}
			break;
		case R.id.llTitle:
			ReportEdit.callIntent(getActivity(), objReport);
			break;
		case R.id.llActionSubmit:
			if (!"".equals(objReport.getApproverEmail())) {
				submitReport();
			} else {
				createDialogInputApproverEmail();
			}

			break;
		case R.id.llApprove:
			objReport.setReportType(getString(R.string.approved_reports));
			objReport.setIsUpdate("1");
			objReport.setIsApproved(1);
			updateReport(objReport);
			showToast(getString(R.string.report_is_approved));
			Util.pushFragmentReceiptBox(new ReportFragment(reportKey, start,
					end), getActivity(), "1");
			break;
		case R.id.llReject:
			objReport.setReportType(getString(R.string.rejected_reports));
			objReport.setIsUpdate("1");
			objReport.setIsApproved(2);
			updateReport(objReport);
			showToast(getString(R.string.report_is_rejected));
			Util.pushFragmentReceiptBox(new ReportFragment(reportKey, start,
					end), getActivity(), "1");
			break;
		case R.id.llUpdate:
			try {
				long mTripID = objTrip.getTripID();
				Util.pushFragmentReceiptBox(new TripDetailFragment("", mTripID,
						false, objReport.getReportID(), reportKey, 0, 0),
						getActivity(), "2");
			} catch (NullPointerException e) {
				e.printStackTrace();
				TripList.callIntentFromReport(getActivity(), reportID);
			}

			break;
		case R.id.llDelete:
			createDialogInfor(
					getString(R.string.are_you_sure_you_want_to_delete), 0);
			break;
		default:
			break;
		}
	}

	/**
	 * show message information
	 */
	private void createDialogInfor(String info, final int action) {
		dialog = new Dialog(getActivity());
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.dialog_message);
		LinearLayout llOk, llCancel;
		TextView txtTitle = (TextView) dialog.findViewById(R.id.txtTitle);
		txtTitle.setText(getString(R.string.messages));
		TextView txtContent = (TextView) dialog.findViewById(R.id.txtContent);
		txtContent.setText(info);
		llOk = (LinearLayout) dialog.findViewById(R.id.llOk);
		llCancel = (LinearLayout) dialog.findViewById(R.id.llCancel);
		llCancel.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Util.HidenKeyBoard(getActivity());
				dialog.dismiss();
			}
		});
		llOk.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				switch (action) {
				case 0:
					objReport.setIsDelete("1");
					updateReport(objReport);
					Util.pushFragmentReceiptBox(new ReportFragment(reportKey,
							start, end), getActivity(), "1");
					break;

				default:
					break;
				}
				dialog.dismiss();
			}
		});
		dialog.show();
	}

	/**
	 * update report
	 */
	private void updateReport(tbl_Report objReport) {

		MenuFragment menuFragment = new MenuFragment();
		if (objReport == null) {
			return;
		}
		int row = 0;
		row = row
				+ getActivity().getContentResolver().update(
						Contract.CONTENT_URI_REPORT,
						objReport.getContentValues(),
						tbl_ReportDao.Properties.ReportID.columnName + " = "
								+ objReport.getReportID(), null);
		menuFragment.resetMenuList(getResources(), getActivity());
	}

	private void animation(boolean isShow) {
		Animation animation = null;
		if (isShow) {
			animation = (Animation) AnimationUtils.loadAnimation(getActivity(),
					R.anim.phone_in_bottom_animation);
			llSubtotal.setVisibility(View.VISIBLE);
			imgArrow.setImageResource(R.drawable.ic_arrow_down);
		} else {
			animation = (Animation) AnimationUtils.loadAnimation(getActivity(),
					R.anim.phone_in_top_animation);
			llSubtotal.setVisibility(View.GONE);
			imgArrow.setImageResource(R.drawable.ic_arrow_up);
		}
		llSubtotal.setAnimation(animation);
		llSubtotal.clearAnimation();
	}

	@Override
	public void doBack(Activity at) {
		ReceiptBox.obBackPress = null;
		Util.pushFragmentReceiptBox(new ReportFragment(reportKey, start, end),
				(FragmentActivity) at, "3");
	}

	/**
	 * Show barbottom depends on report type
	 */
	private void actionShowBarBottom(String mKeyShowBarBottom) {
		actionBarBottomIsGone();
		if (getString(R.string.all_reports).equals(mKeyShowBarBottom)) {
			llDelete.setVisibility(View.VISIBLE);
		} else if (getString(R.string.approved_reports).equals(
				mKeyShowBarBottom)) {
			llAction.setVisibility(View.GONE);
		} else if (getString(R.string.submitted_reports).equals(
				mKeyShowBarBottom)) {
			llAction.setVisibility(View.GONE);
		} else if (getString(R.string.draft_reports).equals(mKeyShowBarBottom)) {
			llUpdate.setVisibility(View.VISIBLE);
			llActionSubmit.setVisibility(View.VISIBLE);
			llDelete.setVisibility(View.VISIBLE);
		} else if (getString(R.string.pending_reports)
				.equals(mKeyShowBarBottom)) {
			llApprove.setVisibility(View.VISIBLE);
			llReject.setVisibility(View.VISIBLE);
		} else if (getString(R.string.rejected_reports).equals(
				mKeyShowBarBottom)) {
			llActionSubmit.setVisibility(View.VISIBLE);
			llDelete.setVisibility(View.VISIBLE);
		}

	}

	/**
	 * Dialog được bật ra khi objectReport thiếu appprover Email
	 */

	private void createDialogInputApproverEmail() {
		dialog = new Dialog(getActivity());
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.dialog_edit_approver);
		LinearLayout llOk, llCancel;
		llOk = (LinearLayout) dialog.findViewById(R.id.llOk);
		llCancel = (LinearLayout) dialog.findViewById(R.id.llCancel);
		llCancel.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Utils.hideKeyboard(getActivity(),
						((EditText) dialog.findViewById(R.id.txtContent)));
				dialog.dismiss();
			}
		});
		llOk.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				String approverEmail = ((TextView) dialog
						.findViewById(R.id.txtContent)).getText().toString();
				if (Util.validateEmail(((TextView) dialog
						.findViewById(R.id.txtContent)))) {

					// update appprover Email
					objReport.setApproverEmail(approverEmail);
					objReport.setIsUpdate("1");
					getActivity().getContentResolver().update(
							Contract.CONTENT_URI_REPORT,
							objReport.getContentValues(),
							tbl_ReportDao.Properties.ReportID.columnName
									+ " = '" + reportID + "'", null);
					submitReport();
					dialog.dismiss();
					Utils.hideKeyboard(getActivity(),
							((EditText) dialog.findViewById(R.id.txtContent)));

				} else {
					Util.setError(
							((EditText) dialog.findViewById(R.id.txtContent)),
							getString(R.string.invalid_email));
				}

			}
		});
		dialog.show();

	}

	/**
	 * Hidden all actions in bar bottom
	 */
	private void actionBarBottomIsGone() {

		llDelete.setVisibility(View.GONE);
		// llArchive.setVisibility(View.GONE);
		llActionSubmit.setVisibility(View.GONE);
		llApprove.setVisibility(View.GONE);
		llReject.setVisibility(View.GONE);
	}

	private float sumTotal(boolean isClaim) {
		float total = 0;
		if (isClaim) {
			txtTotal.setText(getString(R.string.claimed));
		} else {
			txtTotal.setText(getString(R.string.approved));
		}
		arrObjTrip = new ArrayList<tbl_Trip>();
		arrObjTrip = DatabaseSupport.getTripbyReportID(objReport.getReportID()
				+ "", getActivity());
		for (tbl_Trip objTrip : arrObjTrip) {
			ArrayList<tbl_TripItems> arrTripItem = new ArrayList<tbl_TripItems>();
			arrTripItem = DatabaseSupport.getTripItemsByTripID(
					objTrip.getTripID(), getActivity());
			for (tbl_TripItems objTripItem : arrTripItem) {
				if (isClaim) {
					if (objTripItem.getIsClaimed() == 1) {
						total = total + objTripItem.getClaimed();
					}
				} else {
					if (objTripItem.getIsApproved() == 1) {
						total = total + objTripItem.getApproved();
					}
				}

			}
		}
		return total;
	}

	@Override
	public void setTotal() {
		txtMoney.setText("$"
				+ Util.formatStringFloat(sumTotal(objReport.getReportType()
						.equals(getString(R.string.draft_reports)) ? true
						: false)));
	}

	@Override
	public void doOpen(Activity at) {
		Util.HidenKeyBoard(at);
	}

	public static String REPORT_ID_SERVER = "update.report.new";
	public static String REPORT_ID_LOCAL = "update.report.local";
	private ReportUpdateBroadcast reportBroadcast;

	private class ReportUpdateBroadcast extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.hasExtra(REPORT_ID_LOCAL)) {
				if (reportID == intent.getLongExtra(REPORT_ID_LOCAL, 0)) {
					if (intent.hasExtra(REPORT_ID_SERVER)) {
						reportID = intent.getLongExtra(REPORT_ID_SERVER, 0);
					}
					objReport.setReportID(reportID);
				}
			}

		}

	}

}
